package com.origin.src.mybatis.interceptor;

import com.origin.src.mybatis.pojo.TUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.*;


@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class PwdInterceptor implements Interceptor {

    Map<Class<?>, TargetClassField<?>> targetClassFieldMap = new HashMap<>();

    PwdInterceptor() {
        try {
            //初始化，可以在配置文件里或者使用自定义注解配置所有需要加解密的字段
            TargetClassField<TUser> targetClassField = new TargetClassField<>();
            targetClassField.setClassName(TUser.class);
            targetClassField.setFieldName(Collections.singleton(TUser.class.getDeclaredField("loginPassword")));
            targetClassFieldMap.put(targetClassField.getClassName(), targetClassField);

            //反射忽略私有校验
            for (TargetClassField<?> t : targetClassFieldMap.values()) {
                for (Field f : t.getFieldName()) {
                    f.setAccessible(true);
                }
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String methodName = invocation.getMethod().getName();
        if (methodName.equals("query")) {
            return queryInterceptor(invocation);
        } else if (methodName.equals("update")) {
            return updateInterceptor(invocation);
        } else {
            return invocation.proceed();
        }
    }

    @Override
    public Object plugin(Object o) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }


    /**
     * 查询解密
     */
    public Object queryInterceptor(Invocation invocation) throws InvocationTargetException, IllegalAccessException {
        Object obj = invocation.proceed();
        if (obj == null) {
            return null;
        }
        try {
            //查出来是集合或者arrays
            if (obj instanceof Collection<?>) {
                Collection<Object> cs = (Collection) obj;
                if (cs.isEmpty()) {
                    return obj;
                }
                for (Object o : cs) {
                    fieldsDecode(o);
                }
            } else if (obj.getClass().isArray()) {
                Object[] objects = (Object[]) obj;
                if (objects.length == 0) {
                    return obj;
                }
                for (Object o : objects) {
                    fieldsDecode(o);
                }
            } else {
                //其他单条的情况
                fieldsDecode(obj);
            }
        } catch (Exception e) {
            log.error("queryInterceptor error", e);
        }
        return obj;
    }


    /**
     * 插入数据库加密
     */
    public Object updateInterceptor(Invocation invocation) throws InvocationTargetException, IllegalAccessException {
        Object[] objects = invocation.getArgs();
        if (objects == null) {
            return invocation.proceed();
        }
        //入库前加密
        for (Object obj : objects) {
            if (obj == null) {
                continue;
            }
            fieldsEncode(obj);
        }
        Object res = invocation.proceed();
        //入库后解密，args对象调用方可能会继续使用
        for (Object obj : objects) {
            if (obj == null) {
                continue;
            }
            fieldsDecode(obj);
        }
        return res;
    }
    /**
     * 反射字段加密
     */
    public void fieldsEncode(Object o) throws IllegalAccessException {
        if (o == null) {
            return;
        }
        TargetClassField<?> targetClassField = targetClassFieldMap.get(o.getClass());
        if (targetClassField == null) {
            return;
        }
        for (Field field : targetClassField.getFieldName()) {
            field.set(o, encode((String) field.get(o)));
        }
    }
    /**
     * base64解码举例，实际应用可以再加一层AES等
     */
    public String decode(String encText) {
        byte[] bytes = Base64.getDecoder().decode(encText.getBytes(StandardCharsets.UTF_8));
        return new String(bytes, StandardCharsets.UTF_8);
    }


    /**
     * 反射字段解密
     */
    public void fieldsDecode(Object o) throws IllegalAccessException {
        if (o == null) {
            return;
        }
        TargetClassField<?> targetClassField = targetClassFieldMap.get(o.getClass());
        if (targetClassField == null) {
            return;
        }
        for (Field field : targetClassField.getFieldName()) {
            field.set(o, decode((String) field.get(o)));
        }
    }
    /**
     * base64编码举例，实际应用再加一层AES等
     */
    public String encode(String decText) {
        byte[] bytes = Base64.getEncoder().encode(decText.getBytes(StandardCharsets.UTF_8));
        return new String(bytes, StandardCharsets.UTF_8);
    }

}
